/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.dubbo.registry.dubbo;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.bytecode.Wrapper;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.registry.Registry;
import com.alibaba.dubbo.registry.RegistryService;
import com.alibaba.dubbo.registry.integration.RegistryDirectory;
import com.alibaba.dubbo.registry.support.AbstractRegistryFactory;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Protocol;
import com.alibaba.dubbo.rpc.ProxyFactory;
import com.alibaba.dubbo.rpc.cluster.Cluster;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * DubboRegistryFactory
 */
public class DubboRegistryFactory extends AbstractRegistryFactory {

    private Protocol protocol;
    private ProxyFactory proxyFactory;
    private Cluster cluster;

    /**
     * @param url
     * @return
     */
    private static URL getRegistryURL(URL url) {
        return url.setPath(RegistryService.class.getName())
                .removeParameter(Constants.EXPORT_KEY).removeParameter(Constants.REFER_KEY)
                .addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName())
                .addParameter(Constants.CLUSTER_STICKY_KEY, "true")
                .addParameter(Constants.LAZY_CONNECT_KEY, "true")
                .addParameter(Constants.RECONNECT_KEY, "false")
                .addParameterIfAbsent(Constants.TIMEOUT_KEY, "10000")
                .addParameterIfAbsent(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "10000")
                .addParameterIfAbsent(Constants.CONNECT_TIMEOUT_KEY, "10000")
                .addParameter(Constants.METHODS_KEY, StringUtils.join(new HashSet<String>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ","))
                //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName())
                //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch
                //.addParameter(Constants.ON_DISCONNECT_KEY, "disconnect")
                .addParameter("subscribe.1.callback", "true")
                .addParameter("unsubscribe.1.callback", "false");
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public void setProxyFactory(ProxyFactory proxyFactory) {
        this.proxyFactory = proxyFactory;
    }

    public void setCluster(Cluster cluster) {
        this.cluster = cluster;
    }

    /**
     * 1. 根据传入 registryUrl 重新构建 移除 EXPORT_KEY REFER_KEY 添加订阅回调参数
     * dubbo://127.0.0.1:9098/com.alibaba.dubbo.registry.RegistryService?application=demo-provider&callbacks=10000&connect.timeout=10000&dubbo=2.5.4-SNAPSHOT&interface=com.alibaba.dubbo.registry.RegistryService&lazy=true&methods=register,subscribe,unregister,unsubscribe,lookup&owner=william&pid=8492&reconnect=false&sticky=true&subscribe.1.callback=true&timeout=10000&timestamp=1415783872554&unsubscribe.1.callback=false
     * 2. 根据 url 注册服务接口构建注册目录对象 RegistryDircectory,实现了 NotiyfLisener,这里 NotiyfLisener 实现主要是根据 urls 去 refer 引用远程服务 RegistryService 得到对应的 Invoker，
     * 当 urls 变化时重新 refer；目录服务可以列出所有可以执行的 Invoker
     * 3. 利用 cluster 的 join 方法，将 Dirctory 的多个 Invoker 对象伪装成一个 Invoker 对象， 这里
     * 默认集群策略得到 FailoverClusterInvoker
     * <p>
     * 4. FailoverClusterInvoker 利用 ProxyFactory 获取到 RegistryService 服务的代理对象
     * <p>
     * 5. 由 RegistryService 服务的代理对象和 FailoverClusterInvoker 构建 dubbo 协议的注册中心注
     * 册器 DubboRegistry
     * <p>
     * 6. RegistryDircectory 设置注册器 DubboRegistry，设置 dubbo 的协议
     * <p>
     * 7. 调用 RegistryDircectory 的 notify(urls)方法 主要是根据 registryUrls， 引用各个注册中心的 RegistryService 服务实现,将引用的服务
     * 按 key=menthodName/value=invoker 缓存起来, 目录服务 Directory.list(Invocation)会列出所调
     * 用方法的所有 Invoker , 一个 Invoker 代表对一个注册中心的调用实体。
     * <p>
     * 8. 订阅注册中心服务, 服务的提供者调注册中心的服务 RegistryService 属于消费方， 所以
     * 订阅服务的 url 的协议是 consumer consumer://192.168.0.102/com.alibaba.dubbo.registry.RegistryService?application=demo-provider&callbacks=10000&connect.timeout=10000&dubbo=2.5.4-SNAPSHOT&interface=com.alibaba.dubbo.registry.RegistryService&lazy=true&methods=register,subscribe,unregister,unsubscribe,lookup&owner=william&pid=6960&reconnect=false&sticky=true&subscribe.1.callback=true&timeout=10000&timestamp=1415800789364&unsubscribe.1.callback=false
     * 订阅的目的在于在注册中心的数据发送变化的时候反向推送给订阅方
     * directory.subscribe(url)最终调用注册中心的 RegsryService 远程服务， 它是一个普通的
     * dubbo远程调用。要说跟绝大多数dubbo远程调用的区别：url的参数subscribe.1.callback=true
     * 它的意思是 RegistryService 的 subscribe 方法的第二个参数 NotifyListener 暴露为回调服务；
     * url 的参数 unsubscribe.1.callback=false 的意思是 RegistryService 的 unsubscribe 方法的第二个
     * 参数 NotifyListener 暴露的回调服务销毁。
     * 这里dubbo协议的注册中心调注册中心的服务采用的默认集群调用策略是FailOver,选择
     * 一台注册中心，只有当失败的时候才重试其他服务器，注册中心实现也比较简单不具备集群
     * 功能， 如果想要初步的集群功能可以选用 BroadcastCluster 它至少向每个注册中心遍历调用
     * 注册一遍;
     *
     * @param url
     * @return
     */
    public Registry createRegistry(URL url) {
        url = getRegistryURL(url);
        List<URL> urls = new ArrayList<URL>();
        urls.add(url.removeParameter(Constants.BACKUP_KEY));
        String backup = url.getParameter(Constants.BACKUP_KEY);
        if (backup != null && backup.length() > 0) {
            String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(backup);
            for (String address : addresses) {
                urls.add(url.setAddress(address));
            }
        }
        RegistryDirectory<RegistryService> directory = new RegistryDirectory<RegistryService>(RegistryService.class, url.addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString()));
        Invoker<RegistryService> registryInvoker = cluster.join(directory);
        RegistryService registryService = proxyFactory.getProxy(registryInvoker);
        DubboRegistry registry = new DubboRegistry(registryInvoker, registryService);
        directory.setRegistry(registry);
        directory.setProtocol(protocol);
        directory.notify(urls);
        directory.subscribe(new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters()));
        return registry;
    }
}